package com.splic.product.service.impl.thirdRequest;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.splic.common.utils.StringUtils;
import com.splic.product.domain.ExchangeRate;
import com.splic.product.dto.ExchangeRateRequestDto;
import com.splic.product.service.ThirdRequestDataService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 汇率请求三方api
 */
@Slf4j
@Service
public class ExchangeRateRequestServiceImpl implements ThirdRequestDataService {

    private final String host_url = "https://openexchangerates.org/api/latest.json?app_id=";
    private final String appid = "2601c91ffdb842c78b74fe60db78defb";

    @Autowired
    private RestTemplate restTemplate;


    @Override
    public ExchangeRateRequestDto requestThirdData() {
        ExchangeRateRequestDto dto = new ExchangeRateRequestDto();

        String result = restTemplate.getForObject(host_url + appid, String.class);
        if (StringUtils.isEmpty(result)) {
            log.error("获取汇率数据失败");
            return dto;
        }
        List<ExchangeRate> exchangeRateList = Lists.newArrayList();
        JSONObject object = JSONObject.parseObject(result);
        String base = object.getString("base");
        if (object != null && object.get("rates") != null) {
            JSONObject array = object.getJSONObject("rates");
            Map<String, Object> map = array.getInnerMap();
            if(map.isEmpty()){
                return dto;
            }
            final ExchangeRate[] rate = {null};

            map.forEach((key,value)->{
                rate[0] = new ExchangeRate();
                rate[0].setScur(base);
                rate[0].setTcur(key);
                rate[0].setRate(new BigDecimal(value.toString()));
                exchangeRateList.add(rate[0]);
            } );
        }
        dto.setExchangeRateList(exchangeRateList);
        return dto;
    }
}
